﻿using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZYing.QPanel.ViewModels
{
    public class HistoryItemViewModel : ViewModelBase
    {
        public HistoryItemViewModel(ExecutionHistoryEntry entry)
        {
            this.Job = entry.Job;
            this.Trigger = entry.Trigger;
            this.Id = entry.FireInstanceId;
        }

        public string Id { get; }
        public JobKey Job { get; }
        public TriggerKey Trigger { get; }


        public DateTimeOffset? ScheduledFireTime
        {
            get => scheduledFireTime;
            set => SetProperty(ref scheduledFireTime, value);
        }

        public DateTimeOffset ActualFireTime
        {
            get => actualFireTime;
            set => SetProperty(ref actualFireTime, value);
        }

        private TimeSpan _runTime;
        private DateTimeOffset? scheduledFireTime;
        private DateTimeOffset actualFireTime;

        public TimeSpan RunTime
        {
            get { return _runTime; }
            set { SetProperty(ref _runTime, value); }
        }
        private DateTimeOffset? _finishedTime;

        public DateTimeOffset? FinishedTime
        {
            get { return _finishedTime; }
            set { SetProperty(ref _finishedTime, value); }
        }
        private string _status;

        public string Status
        {
            get { return _status; }
            set { SetProperty(ref _status, value); }
        }

        public async void Read(ExecutionHistoryEntry entry, IExecutionHistoryStore store)
        {
            if (entry == null) return;
            this.ScheduledFireTime = entry.ScheduledFireTimeUtc;
            this.ActualFireTime = entry.ActualFireTimeUtc;
            this.FinishedTime = entry.FinishedTimeUtc;
            if (this.FinishedTime != null)
            {
                this.RunTime = this.ActualFireTime - this.FinishedTime.Value;
            }
            else
            {
                this.RunTime = this.ActualFireTime - DateTimeOffset.UtcNow;
            }
            JobState = entry.GetJobState();
            if (!string.IsNullOrWhiteSpace(entry.ExceptionMessage))
            {
                Status = entry.ExceptionMessage;
            }
            else if (store != null)
            {
                var log = await store.FindLastLog(this.Job, this.Id);
                if (log != null) this.Status = log.Status;
            }
        }
        private JobState? _jobState;

        public JobState? JobState
        {
            get { return _jobState; }
            set { SetProperty(ref _jobState, value); }
        }

    }
}
